package com.et114.core.utility;

import java.util.*;
import java.io.*;

/**
 *
 * <p>Title: 报表中心</p>
 * <p>Description: 报表中心</p>
 * <p>Copyright: Copyright (c) 2007</p>
 * <p>Company: 润乾报表</p>
 * @author guanhw
 * @version 1.0
 */
public class FileUtils
        extends java.io.File {

        /**
         *
         */
        private static final long serialVersionUID = 1L;
        private static java.io.File m_root;
        private static ArrayList m_dirs;
        FileUtils(java.io.File file, String str) {
                super(file, str);
        }

        FileUtils(String str1, String str2) {
                super(str1, str2);
        }

        FileUtils(String str) {
                super(str);
        }

        FileUtils(java.net.URI uri) {
                super(uri);
        }

        public static void deleteDirs(java.io.File dir) throws Exception {
                m_root = dir;
                m_dirs = new ArrayList();
                if (!m_root.isDirectory()) {
                        throw new Exception("Exception:\"" + m_root.toString()
                                            + "\" is not a director");
                }
                else {
                        for (int i = 0; i < m_dirs.size(); i++) {
                                System.out.println( ( (FileUtils) m_dirs.get(i)).
                                        toString());
                        }
                        // delete all director
                        try {
                                m_dirs.add(m_root);
                                myDelete();
                        }
                        catch (Exception e) {
                                e.printStackTrace();
                        }
                }
        }

        /**
         *
         * @param dirPath
         *            String a director file path;
         * @throws IOException
         *             if dirPath is not a director file path
         */
        public static void deleteDirs(String dirPath) throws Exception {
                m_root = new java.io.File(dirPath);
                deleteDirs(m_root);
        }

        public static void deleteSubDirs(String dirPath) throws Exception {
                m_root = new java.io.File(dirPath);
                deleteSubDirs(m_root);
        }

        public static void deleteSubDirs(java.io.File dir) throws Exception {
                m_root = dir;
                m_dirs = new ArrayList();
                // deleteDirs(m_root);
                if (!m_root.isDirectory()) {
                        throw new Exception("Exception:\"" + m_root.toString()
                                            + "\" is not a director");
                }

                else {
                        for (int i = 0; i < m_dirs.size(); i++) {
                                System.out.println( ( (FileUtils) m_dirs.get(i)).
                                        toString());
                        }
                        try {
                                myDelete();
                        }
                        catch (Exception e) {
                                e.printStackTrace();
                        }
                }
        }

        /*
         * visit all a director and save them in a list
         */
        private static void visitAll(java.io.File tempRoot) {
                java.io.File[] dirs = tempRoot.listFiles();
                if (dirs != null) {
                        List dirsList = Arrays.asList(dirs);
                        if (dirsList == null) {
                                try {
                                        tempRoot.delete();
                                }
                                catch (Exception e) {
                                        e.printStackTrace();
                                }
                        }
                        else {
                                m_dirs.addAll(dirsList);
                                for (int i = 0; i < dirsList.size(); i++) {
                                        tempRoot = (java.io.File) dirsList.get(
                                                i);
                                        visitAll(tempRoot);
                                }
                        }
                }
        }

        /*
         * do delete
         */
        private static void myDelete() throws Exception {
                // m_dirs.add(m_root);
                visitAll(m_root);
                if (m_dirs != null) {
                        for (int i = m_dirs.size() - 1; i >= 0; i--) {
                                java.io.File f = (java.io.File) m_dirs.remove(i);
                                String fileName = f.toString();

                                if (!f.delete()) {
                                        throw new Exception(
                                                "Exception: delete file " +
                                                fileName
                                                + " false!");
                                }
                        }
                }
                else {
                        throw new Exception("Exception: read file list of "
                                            + m_root.toString() + "false!");
                }
        }

        /**
         * @file1:目标文件夹
         * @file2:拷贝文件夹
         * @mark:true:cut false:copy
         * Map key:原始路径  value:改变后的路径
         * 返回改变路径名称
         */
        public static Map copyDirectiory(String file1, String file2,
                                         boolean mark) throws IOException {
                Map map = new HashMap();
                (new File(file1)).mkdirs();
                File[] file = (new File(file2)).listFiles();
                for (int i = 0; i < file.length; i++) {
                        if (file[i].isFile()) {
                                FileInputStream input = new FileInputStream(
                                        file[i]);
                                FileOutputStream output = new FileOutputStream(
                                        file1 + "/"
                                        + file[i].getName());
                                byte[] b = new byte[1024 * 5];
                                int len;
                                while ( (len = input.read(b)) != -1) {
                                        output.write(b, 0, len);
                                }
                                output.flush();
                                output.close();
                                input.close();
                                //
                                if (mark) {
                                        map.put(file[i],
                                                file1 + "/" + file[i].getName());
                                }
                        }
                        if (file[i].isDirectory()) {
                                map.putAll(copyDirectiory(file1 + "/" +
                                        file[i].getName(), file2 + "/"
                                        + file[i].getName(), mark));
                        }
                }

                if (mark) {
                        try {
                                deleteDirs(file2);
                        }
                        catch (Exception e) {
                                System.err.println("删除失败！");
                                e.printStackTrace();
                        }
                }
                return map;
        }

        /**
         * 把该文件拷贝到完整的路径中去
         *
         * @param file文件句柄
         * @param path文件目标的绝对路径
         * @return
         */
        public static boolean copy(File file, String fullPath, boolean mark) {
                String fileName = file.getName();
                int pos = fileName.lastIndexOf(File.separator);
                if (pos > 0) {
                        fileName = fileName.substring(pos + 1, fileName.length());
                }
                String lastPath = fullPath + File.separator + fileName;
              System.out.println ("##lastPath:"+lastPath);
                File objFile = new File(lastPath);
                if (objFile.exists() && !objFile.delete()) { // 如果存在则删除
                        System.err.println("删除目标文件失败");
                        return false;
                }
                // 开始拷贝
                try {
                        objFile.createNewFile();
                        FileInputStream fis = new FileInputStream(file);
                        FileOutputStream fos = new FileOutputStream(objFile);
                        byte[] buf = new byte[1024];
                        int i = 0;
                        while ( (i = fis.read(buf)) != -1) {
                                fos.write(buf, 0, i);
                        }
                        fis.close();
                        fos.close();
                        if (mark) {
                                return file.delete();
                        }
                }
                catch (IOException ie) {
                        ie.printStackTrace();
                        return false;
                }
                return true;
        }
        
        public static String copy2(File file, String fullPath, boolean mark) {
            String fileName = file.getName();
            int pos = fileName.lastIndexOf(File.separator);
            if (pos > 0) {
                    fileName = fileName.substring(pos + 1, fileName.length());
            }
            //fileName=System.currentTimeMillis ( )+fileName;
            String lastPath = fullPath + "/" + fileName; 
            File objFile = new File(lastPath);
            if (objFile.exists() && !objFile.delete()) { // 如果存在则删除
                    System.err.println("删除目标文件失败");
                    return null;
            }
            // 开始拷贝
            try {
                    objFile.createNewFile();
                    FileInputStream fis = new FileInputStream(file);
                    FileOutputStream fos = new FileOutputStream(lastPath);
                    byte[] buf = new byte[1024];
                    int i = 0;
                    while ( (i = fis.read(buf)) != -1) {
                            fos.write(buf, 0, i);
                    }
                    fis.close();
                    fos.close();
            }
            catch (IOException ie) {
                    ie.printStackTrace();
                    return null;
            }
            return fileName;
    }

        /**
         *
         * @param file
         * @return
         * @throws IOException
         */
        public static byte[] getBytesFromFile(File file) throws IOException {
                InputStream is = new FileInputStream(file);
                long length = file.length();
                if (length > Integer.MAX_VALUE) {
                }
                byte[] bytes = new byte[ (int) length];
                int offset = 0;
                int numRead = 0;
                while (offset < bytes.length
                       &&
                       (numRead = is.read(bytes, offset, bytes.length - offset)) >=
                       0) {
                        offset += numRead;
                }
                if (offset < bytes.length) {
                        throw new IOException("Could not completely read file "
                                              + file.getName());
                }
                is.close();
                return bytes;
        }

        protected static final int DEFAULT_BUFFER_SIZE = 4096;

        public static boolean exists(String file) {
                boolean mark = false;
                try {
                        mark = new File(file).exists();
                }
                catch (Exception e) {
                        e.printStackTrace();
                }
                return mark;
        }
        
        public static File[] listSortedFiles(File dirFile) {   
            assert dirFile.isDirectory();   
          
                File[] files = dirFile.listFiles();   
                   
                FileWrapper [] fileWrappers = new FileWrapper[files.length];   
                for (int i=0; i<files.length; i++) {   
                    fileWrappers[i] = new FileWrapper(files[i]);   
                }   
                   
                Arrays.sort(fileWrappers);   
                   
                File []sortedFiles = new File[files.length];   
                for (int i=0; i<files.length; i++) {   
                    sortedFiles[i] = fileWrappers[i].getFile();   
                }   
                   
                return sortedFiles;   
            }   
        
          
          

        

}
class FileWrapper implements Comparable {   
    /** File */  
    private File file;   
       
    public FileWrapper(File file) {   
        this.file = file;   
    }   
        
    public int compareTo(Object obj) {   
        assert obj instanceof FileWrapper;   
           
        FileWrapper castObj = (FileWrapper)obj;   
                   
        if (this.file.getName().compareTo(castObj.getFile().getName()) > 0) {   
            return 1;   
        } else if (this.file.getName().compareTo(castObj.getFile().getName()) < 0) {   
            return -1;   
        } else {   
            return 0;   
        }   
    }   
       
    public File getFile() {   
        return this.file;   
    }   
}  